#include "mainwindow.h"
#include "ui_mainwindow.h" 

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    qDebug() << "主线程：" << QThread::currentThread();

    //初始化显示端口信息
    serialScan();

    //初始化状态栏
    QStatusBar *statusBar = ui->statusbar;
    this->setStatusBar(statusBar);

    //初始化信号灯
    ui->widget_light->setStyleSheet(
        "background-color: qradialgradient(spread:pad, cx:0.5, cy:0.5, "
        "radius:0.5, fx:0.5, fy:0.5, stop:0 rgba(255, 2, 0, 255), stop:1 "
        "rgba(255, 255, 255, 255));border-radius:12px;");

    //周期刷新串口信息
    timer_serial->setInterval(3456);//每3.4秒检查一次[只要不超过5s都不影响使用体验]
    timer_serial->start();
    connect(timer_serial,&QTimer::timeout,[=](){
        ui->combo_port->clear();
        serialScan();
    });

    //初始化图表
    chartInit();

    //初始化滚动条
    ui->m_ScrollBar->setRange(0,25);
    connect(ui->m_ScrollBar,&QScrollBar::valueChanged,this,&MainWindow::onScrollBarMoved);

    // ser1->moveToThread(thread_serial);
    // thread_serial->start();

    connect(ui->btn_connect,&QPushButton::clicked,this,&MainWindow::connectClicked);
    connect(ui->btn_send,&QPushButton::clicked,ser1,[=]{
        emit sender(ui->lineEdit->text());
        /* emit test(i,i*3.1415926);
             i++;
           qDebug() << "11";*/
    });
    connect(ui->btn_sendContinue,&QPushButton::clicked,this,&MainWindow::testSin);
    connect(this,&MainWindow::sender,ser1,&Serial::PortSend);

    //接收到串口数据进行实时更新
    connect(ser1,&Serial::dataUpdate,this,&MainWindow::chartDraw);

    connect(this,&MainWindow::test,ser1,&Serial::test);
}

void MainWindow::connectClicked()
{
    if(ser1->isOpen == 0)//链接成功
    {
        ser1->PortOpen(ui->combo_port->currentText(),QSerialPort::Baud115200);
        {
            if(ser1->isOpen==1)
            {
                ui->btn_connect->setText("关闭串口");
                ui->widget_light->setStyleSheet(
                    "background-color: qradialgradient(spread:pad, cx:0.5, cy:0.5, "
                    "radius:0.5, fx:0.5, fy:0.5, stop:0 rgba(0, 229, 0, 255), stop:1 "
                    "rgba(255, 255, 255, 255));border-radius:12px;");
                QString status_str = ui->combo_port->currentText()+"连接成功，波特率";
                this->statusBar()->showMessage(status_str,0);
            }
            else
            {
                QString status_str = ui->combo_port->currentText()+"打开失败！";
                this->statusBar()->showMessage(status_str,0);
                qDebug() << "Failed";
            }
        }
    }
    else
    {
        ser1->PortClose();
        if(ser1->isOpen == 0)
        {
            ui->btn_connect->setText("打开串口");
            ui->widget_light->setStyleSheet(
                "background-color: qradialgradient(spread:pad, cx:0.5, cy:0.5, "
                "radius:0.5, fx:0.5, fy:0.5, stop:0 rgba(255, 0, 0, 255), stop:1 "
                "rgba(255, 255, 255, 255));border-radius:12px;");            
            QString status_str = ui->combo_port->currentText()+"关闭成功";
            this->statusBar()->showMessage(status_str,0);
        }
    }
}

void MainWindow::testSin()
{
    QTimer *timer = new QTimer(this);//100ms延时进行绘制
    timer->setInterval(10);//设置延时时间为100ms
    timer->start();
    int count = 1;
    connect(timer,&QTimer::timeout,this,[=]()mutable{
        int num = (int)5.0*sin(count*M_PI/180)*100;
        num = (num < 0) ? (65536 + num) : num;
        QString send_str = QString::number(num,16).toUpper().rightJustified(4,QLatin1Char('0'));
        send_str.insert(2,' ');
        qDebug() << send_str;
        emit sender(send_str);
        count++;
        if(count > 800)
            timer->stop();
    });//mutable关键字允许lambda表达式内的代码修改按值捕获的变量
}

void MainWindow::chartInit()
{
    chart->setTitle("数据1");
    series->setName(tr("Data 1"));
    series->setColor(Qt::red);
    series->setPen(QPen(Qt::red,2));
    chart->addSeries(series);

    //设置X轴属性    
    chart->addAxis(axisX,Qt::AlignBottom);
    axisX->setRange(0,36);
    axisX->setTitleText("Time(s)");
    series->attachAxis(axisX);

    //设置Y轴属性
    chart->addAxis(axisY,Qt::AlignLeft);
    axisY->setRange(-5,5);
    axisY->setTitleText("数值");
    series->attachAxis(axisY);

    ui->chart_data1->setChart(chart);
}

void MainWindow::chartDraw(int i,double data)
{
    series->append(i,data);
    qDebug() << "chartDraw" << i << "," << data;
    if(series->count() > 10)
    {
        ui->m_ScrollBar->setRange(0,i-10);//重点
    }
}

void MainWindow::chartMove(int cIndex)
{
    qDebug() << "currentIndex:" << cIndex;
     int minX = series->points().at(cIndex).x();
     double maxX = series->points().last().x();

     double targetMinX = minX + 1;
     double targetMaxX = maxX + 1;

     qDebug() << "targetMinX:" << targetMinX << "targetMaxX:" << targetMaxX;
     axisX->setRange(targetMinX,targetMaxX);
     currentIndex++;
}

//串口数据扫描
void MainWindow::serialScan()
{
    QString portName;//串口名称
    const auto infos = QSerialPortInfo::availablePorts();//查询可用端口
    for(const QSerialPortInfo &info : infos){
        //qDebug() << "description():" << info.description();

        QStringList list;
        //descri = info.description();//串口描述
        //serialNumber = info.serialNumber();//串口序列号
        portName = info.portName();//串口名称
        //qDebug() << "串口信息:" << portName ;
        ui->combo_port->addItem(portName,0);
    }
}

void MainWindow::onScrollBarMoved(int value)
{
    // 更新X轴的范围，以实现滚动效果
    axisX->setRange(value,value+10);
}

MainWindow::~MainWindow()
{
    ser1->~Serial();
    delete ui;
}
